package com.lsl.rdf.result.page;

import com.github.pagehelper.PageInfo;
import com.lsl.rdf.callback.PageResultCallback;
import com.lsl.rdf.utils.bean.IBeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 分页响应结果对象
 * <p>
 * Created by lsl on 2021/6/2.
 */
public class PageResult<T> extends PageInfo<T> implements Serializable {

    public PageResult(List<T> list) {
        super(list);
    }

    /**
     * list 转PageResult对象
     *
     * @param list list
     * @param <T>  list类型
     * @return pageResult
     */
    public static <T> PageResult<T> of(List<T> list) {
        return new PageResult<>(list);
    }

    /**
     * pageInfo 转PageResult对象
     *
     * @param pageInfo pageInfo对象
     * @param target   转换对象class
     * @param <T>      转换对象类型
     * @return pageResult
     */
    public static <T> PageResult<T> of(PageInfo<?> pageInfo, Supplier<T> target) {
        return of(pageInfo, target, null);
    }

    /**
     * pageInfo 转PageResult对象
     *
     * @param pageInfo pageInfo对象
     * @param target   转换对象class
     * @param callback 回调方法
     * @param <S>      转换对象原类型
     * @param <T>      转换对象类型
     * @return pageResult
     */
    public static <S, T> PageResult<T> of(PageInfo<S> pageInfo, Supplier<T> target, PageResultCallback<S, T> callback) {
        if (Objects.isNull(pageInfo) || Objects.isNull(target)) {
            return new PageResult<>(Collections.emptyList());
        }
        if (CollectionUtils.isEmpty(pageInfo.getList())) {
            return new PageResult<>(Collections.emptyList());
        }
        List<T> list = new ArrayList<>(pageInfo.getList().size());
        for (S source : pageInfo.getList()) {
            T t = IBeanUtil.copyInstance(source, target);
            if (Objects.nonNull(callback)) {
                callback.callback(source, t);
            }
            list.add(t);
        }
        PageResult<T> pageResult = new PageResult<>(list);
        BeanUtils.copyProperties(pageInfo, pageResult, "list");
        return pageResult;
    }
}
